import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { useLocalStorage } from '@/hooks'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import { userStores } from '@/stores/modules/user'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false });
const whiteList: string[] = ['/login', '/register'];
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  // 确定用户是否已登录
  const hasToken = useLocalStorage.getItem('token')
  const userInfo = JSON.parse(useLocalStorage.getItem('userInfo'))
  // 判断是否登录
  if (hasToken && userInfo) {
    if (to.path === '/login') {
      next({ path: '/' })
      ElMessage.warning('您已登录，无需再次登录！')
      NProgress.done()
    } else {
      const hasGetUserInfo = userInfo.userId
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 获取用户信息
          await userStores().getUserInfo()
          next()
        } catch (error) {
          // 删除存储的登录信息，重定向到登录页
          await userStores().resetToken()
          ElMessage.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    // 没有登录信息
    if (whiteList.indexOf(to.path) !== -1) {
      // 在白名单中设置，直接进入
      next()
    } else {
      // 其他无权访问的页面将重定向到登录页面。
      next(`/login`)
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})
